#include <buola/term.h>

#include <buola/gui.h>
#include <buola/gui/cmenu.h>
#include <buola/widgets/ctoolbar.h>
#include <buola/widgets/ctabbox.h>
#include <buola/gui/cicon.h>

#include <buola/term/ctermwindow.h>

namespace buola {

using namespace gui;
    
CTermWindow::CTermWindow()
{
    SetWindowActions(EWindowActions::HIDE|EWindowActions::DOCK|EWindowActions::MINIMIZE);
    SetTitle(L"terminal");

    Resize(CSize_d(600,600));

    mTabBox=new CTabBox;
    mTabBox->eActivated.Connect(&CTermWindow::OnTab,this,_1);
    mTabBox->SetStyle(TABBOX_TEXT|TABBOX_TOP|TABBOX_HIDEIFONE|TABBOX_UNDERTB);
    Attach(mTabBox,gui::ATTACH_REPLACECLIENT);

    mMenu=new CMenu;

//  FillToolBar();

//  mToolBar=new CToolBar;
//  mToolBar->CreateAndSet(this,mMenu);

//  mToolBar->Show();
    mCurTerm=nullptr;
}

void CTermWindow::FillToolBar()
{
}

CTermWindow::SPack *CTermWindow::GetTerm(CTabBoxItem *pItem)
{
    for(int i=0;i<mTerms.size();i++)
    {
        if(pItem==mTerms[i]->mItem)
            return mTerms[i].get();
    }
    
    return nullptr;
}

CTermWindow::SPack *CTermWindow::NewPack(const std::wstring &pText)
{
    SPack *lPack=new SPack;
    lPack->mTitle=pText;
    lPack->mBox=new CTermBox;
    lPack->mItem=mTabBox->AddItem(pText,nullptr,lPack->mBox);
    mTerms.emplace_back(lPack);
    lPack->mBox->SetFocus();
    lPack->mBox->sTitleChanged.Connect(&CTermWindow::OnTitleChanged,this,lPack);
    mTabBox->SelectItem(lPack->mItem->mID);
    return lPack;
}

void CTermWindow::OpenApp(const std::string &pCmd)
{
    SPack *lPack=NewPack(utf32(pCmd));
    lPack->mBox->OpenApp(pCmd);
}

void CTermWindow::OpenShell()
{
    SPack *lPack=NewPack(L"shell");
    lPack->mBox->OpenShell();
}

void CTermWindow::OnTab(CTabBoxItem *pItem)
{
    SPack *lPack=GetTerm(pItem);

    SetTitle(L"terminal - "+lPack->mBox->GetTitle());
    
    mCurTerm=GetTerm(pItem);
}

void CTermWindow::OnTitleChanged(SPack *pPack)
{
    std::wstring lTitle=pPack->mBox->GetTitle();
    if(pPack->mItem->mID==mTabBox->GetSelItem())
    {
        SetTitle(L"terminal - "+lTitle);
    }

    if(lTitle.length()>18)
        lTitle=lTitle.substr(0,8)+L" ... "+lTitle.substr(lTitle.length()-8);

    mTabBox->SetItemText(pPack->mItem->mID,lTitle);
}

const PTermWindow &CTermWindow::GetTermWindow()
{
    static PTermWindow lWindow;
    
    if(!lWindow)
        lWindow=new CTermWindow;
    
    return lWindow;
}

/*namespace buola*/ }
